import { Component, OnInit, OnDestroy } from '@angular/core';
import { ManhuaImageProvider } from './manhua.image.provider';
import { Util } from '../../../util/util';
import { Subscription } from 'rxjs/Subscription';
import { Router } from '@angular/router';

@Component({
    selector: 'manhua-image',
    templateUrl: './manhua.image.html',
    styleUrls: ['./manhua.image.css'],
    providers: [ManhuaImageProvider]
})

export class ManhuaImage {

    manhua: any;

    img: string = "/assets/images/loading.gif";

    page: any = {
        curpage: 1,
        pages: 0,
    };

    title: string = '';

    constructor(private service: ManhuaImageProvider, private util: Util, private router: Router) {
        this.manhua = this.util.sessionStore().get('manhuaImageData');
    }

    ngOnInit() {
        this.init();
    }

    init() {
        this.img = "/assets/images/loading.gif";
        this.title = this.manhua.cur_chapter.chapter;
        this.page = {
            curpage: 1,
            pages: 0,
        };

        this.chapterIndexFun();
        this.ImageLoadParam = {};
        this.getImageLoadParam();
    }

    // 
    ngOnDestroy() {
        if (this.ImageLoadParamSub) {
            this.ImageLoadParamSub.unsubscribe();
        }
        if (this.getImageLoadSub) {
            this.getImageLoadSub.unsubscribe();
        }
    }



    chapterIndex: number = 0;
    chapterLink = {
        next: '',
        pre: ''
    };
    chapterIndexFun() {
        let chapters = this.manhua['chapters'];

        for (let i = 0; i < chapters.length; i++) {
            if (chapters[i]['href'] === this.manhua['cur_chapter']['href']) {
                this.chapterIndex = i;
                console.log(i);
                break;
            }
        }

        let _pre = this.chapterIndex - 1;
        if (_pre >= 0) {
            this.chapterLink.pre = chapters[_pre];
        } else {
            this.chapterLink.pre = null;
        }

        let _next = this.chapterIndex + 1;
        if (_next <= chapters.length - 1) {
            this.chapterLink.next = chapters[_next];
        } else {
            this.chapterLink.next = null;
        }



    }


    // 去下一个章节
    goToChapter(_chapter) {
        this.manhua['cur_chapter'] = _chapter;

        console.log(this.manhua);

        this.util.sessionStore().set('manhuaImageData', this.manhua);

        this.router.navigate(['/manhua', this.manhua.title, this.manhua['cur_chapter']['chapter']]);

        this.init();
    }

    // 返回
    goBackRouter() {
        this.router.navigate(['/manhua', this.manhua.title]);
    }

    // 跳转
    go(page) {
        this.ImageLoadParam['page'] = page;
        this.page.curpage = this.ImageLoadParam['page'];
        this.getImageLoad(this.ImageLoadParam);
    }

    // 上一页
    pre() {

        if (this.ImageLoadParam['page'] == 1) {
            return;
        }
        this.ImageLoadParam['page']--;

        this.page.curpage = this.ImageLoadParam['page'];
        this.getImageLoad(this.ImageLoadParam);
    }

    // 下一页
    next() {

        if (this.ImageLoadParam['page'] == this.ImageLoadParam['totalPage']) {
            // 是否有下一个章节
            if (this.chapterLink.next) {
                this.goToChapter(this.chapterLink.next);
            }
            return;

        }

        this.ImageLoadParam['page']++;
        this.page.curpage = this.ImageLoadParam['page'];
        this.getImageLoad(this.ImageLoadParam);
        window.scroll(0, 0);
    }


    // 获取请求参数
    ImageLoadParamSub: Subscription;
    ImageLoadParam: any;
    getImageLoadParam() {
        let json = {
            url: this.manhua['cur_chapter']['href']
        };

        this.ImageLoadParamSub = this.service.getParam(this.manhua).subscribe((res: any) => {
            console.log(res);
            if (res.success) {

                switch (this.manhua['domain']) {
                    case 'www.1kkk.com':
                    case 'http://www.1kkk.com':
                        this.ImageLoadParam = res.data;
                        this.page.pages = this.ImageLoadParam['totalPage'];
                        this.getImageLoad(this.ImageLoadParam);
                        break;
                    case 'manhua.dmzj.com':
                    case "http://manhua.dmzj.com":

                        let _pages = eval(res.data.totalPage);

                        let arry = _pages.split('pages=');

                        _pages = eval(eval(arry[2]));

                        for (let j = 0; j < _pages.length; j++) {

                            let imageUrl = "https://images.dmzj.com/" + _pages[j];

                            imageUrl = "/api/manhua/img?&Referer=" + encodeURIComponent(this.manhua.cur_chapter.href.replace('http', 'https')) + "&url=" + imageUrl;

                            _pages[j] = imageUrl;

                            console.log(imageUrl);

                            this.preLoadImage(imageUrl, function (img) {
                                img = null;
                            });

                            if (j == 0) {
                                this.img = imageUrl;
                            }

                        }

                        this.ImageLoadParam = {
                            totalPage: _pages.length,
                            page: res.data.page,
                            imgUrls: _pages
                        };

                        this.page.pages = this.ImageLoadParam['totalPage'];
                        this.getImageLoad(this.ImageLoadParam);
                        break;
                    case 'http://www.manhuagui.com':
                        // ??
                        break;
                    default:
                        break;
                }


                // 分页
                // this.pagePagination(this.page);



            } else {
                this.ImageLoadParam = null;
            }
        }, (err: any) => {

        });
    }

    // jsonp
    getImageLoadSub: Subscription;
    getImageLoad(data) {

        // console.log(data);
        // let json = {
        //     Referer: this.manhua.cur_chapter.href,
        //     url: this.manhua.cur_chapter.href + "chapterfun.ashx",
        //     data: data
        // };

        switch (this.manhua['domain']) {
            case 'www.1kkk.com':
            case 'http://www.1kkk.com':
                this._1kkkImageHandel(data);
                break;

            case 'manhua.dmzj.com':
            case 'http://manhua.dmzj.com':
                this.dmzjImageHandel(data);
                break;
            case 'http://www.manhuagui.com':
                this.mhgImageHandel(data);
                break;
            default:
                break;
        }

    }




    preLoadImage(url, callback) {
        var img = new Image(); //创建一个Image对象，实现图片的预下载    
        img.onload = function () {
            img.onload = null;
            callback(img);
        };
        img.src = url;
    }


    // 1kkk漫画图片处理
    _1kkkImageHandel(data) {

        let json = {
            Referer: this.manhua.cur_chapter.href,
            url: this.manhua.cur_chapter.href + "chapterfun.ashx",
            data: data
        };

        this.getImageLoadSub = this.service.get1kkkImage(json).subscribe((res: any) => {
            console.log(res);

            if (res.success) {
                let fun = res.data;

                let arry = eval(fun);
                // http://manhua1032-61-174-50-98.cdndm5.com/41/40631/577102/1_3094.jpg?cid=577102&key=255258e02d0e050045b1a81217b25132

                for (let j = 0; j < arry.length; j++) {

                    let imageUrl = arry[j];

                    imageUrl = "/api/manhua/img?&Referer=" + encodeURIComponent(this.manhua.cur_chapter.href) + "&url=" + encodeURIComponent(imageUrl);
                    console.log(imageUrl);
                    this.preLoadImage(imageUrl, function (img) {
                        img = null;
                    });

                    if (j == 0) {
                        this.img = imageUrl;

                    }

                }
            } else {
                this.img = null;
            }

        }, (err: any) => {
            console.log(err);
        });






    }

    // 动漫之家漫画图片处理
    dmzjImageHandel(data) {
        console.log(data);

        let page = data.page;

        // let imageUrl = "https://images.dmzj.com/"+data.imgUrls[page];

        // console.log(imageUrl);

        // this.img = "/api/manhua/img?&Referer=" + encodeURIComponent(this.manhua.cur_chapter.href.replace('http','https')) + "&url=" + imageUrl;


        this.img = data.imgUrls[page - 1];


    }

    // 
    mhgImageHandel(data) {
        console.log(data);

        let page = data.page;

        this.img = data.imgUrls[page - 1];
    }
}